package ph.com.gs3.formalistics.view.document.specialfields;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.vo.business.form.FormFieldData;
import ph.com.gs3.formalistics.view.document.abstractfields.SpecialFieldView;
import android.content.Context;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AttachmentField extends SpecialFieldView {

	public static final String TAG = AttachmentField.class.getSimpleName();

	private String attachmentLink;

	private TextView tvLabel;
	private TextView tvAttachmentLink;
	private Button bBrowse;

	public AttachmentField(Context context, FormFieldData formField) {
		super(context, formField);

		setLabel(formField.getLabel());

		if (formField.getValue() != null && !formField.getValue().trim().isEmpty()) {
			setValue(formField.getValue());
		}
	}

	@Override
	protected void createView() {

		LayoutInflater.from(getContext()).inflate(R.layout.field_attachment, this, true);

		tvLabel = (TextView) findViewById(R.id.Attachment_tvLabel);
		tvAttachmentLink = (TextView) findViewById(R.id.Attachment_tvLink);
		bBrowse = (Button) findViewById(R.id.Attachment_bBrowse);

		bBrowse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});

	}

	@Override
	protected void setFieldId(String fieldId) {
		this.setTag(fieldId + "_container");
		this.tvAttachmentLink.setTag(fieldId);
	}

	public void setLabel(String label) {
		tvLabel.setText(label);
	}

	public void setValue(String attachmentLink) {

		this.attachmentLink = attachmentLink;

		String fileName = getFileName(attachmentLink);
		String linkHTML = "<a href=\"" + attachmentLink + "\">" + fileName + "</a>";

		tvAttachmentLink.setText(Html.fromHtml(linkHTML));
		tvAttachmentLink.setMovementMethod(LinkMovementMethod.getInstance());

	}

	public String getValue() {
		return attachmentLink;
	}

	public String getFileName() {
		return getFileName(attachmentLink);
	}

	private String getFileName(String attachmentLink) {

		if (attachmentLink.contains("/")) {
			String[] pieces = attachmentLink.split("/");
			return pieces[pieces.length - 1];
		}

		return null;

	}

	@Override
	protected void initializeChangeListener() {}

	@Override
    public void showError(String errorMessage) {
	   FLLogger.e(TAG, "showError not yet supported");
    }

}
